package de.dhbw.ka.tit09.picsim.io;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import de.dhbw.ka.tit09.picsim.model.Command;
import de.dhbw.ka.tit09.picsim.model.ProgramCode;
import de.dhbw.ka.tit09.picsim.model.SourceText;

/**
 * Class for assembler file handling. Reads assembler files and parses contents.
 * 
 * @author Andreas Bender
 * 
 */
public class FileHandler {
	/**
	 * Reads the content of a given file and returns the content represented in
	 * an {@link ProgramCode} object.
	 * 
	 * @param uri the file URI
	 * @return the parsed file contentsF
	 */
	public static ProgramCode readFileContent(String uri) {
		File file = new File(uri);

		return parseFile(file);
	}

	private static ProgramCode parseFile(File file) {
		List<Command> commandList = new ArrayList<Command>();
		List<SourceText> textList = new ArrayList<SourceText>();

		BufferedReader in = null;
		try {
			in = new BufferedReader(new FileReader(file));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		String line = null;
		try {
			line = in.readLine();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		while (line != null) {

			if (line.charAt(0) == ' ') {
				textList.add(new SourceText(line.substring(27), false));
			} else {
				commandList.add(new Command(Integer.parseInt(
						line.substring(5, 9), 16), Integer.parseInt(line
						.substring(20, 25)) - 1));

				textList.add(new SourceText(line.substring(27), true));
			}

			try {
				line = in.readLine();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return new ProgramCode(commandList, textList);
	}
}
